package com.xhis.homenurse;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.xhis.homenurse.tools.DialogTools;

/**
 * 程序更新下载界面
 *
 * @author 张兵
 */
public class AppUpdaterActivity extends AppCompatActivity
{
    private Toolbar mToolbar;
    private AlertDialog dialog;
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private GLobalApp mGlobalApp;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appupdater);
        mGlobalApp = (GLobalApp) getApplicationContext();
        mGlobalApp.addActivity(this);
        mToolbar = (Toolbar) findViewById(R.id.activity_appupdater_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                exit();
            }
        });

        if (requestPermission()) {
            thread = new AppUpdaterActivity.DownThread();
            thread.start();
        } else {
            startRequestPermission();
        }
    }

    private AppUpdaterActivity.DownThread thread;
    private boolean isDownload = false;

    /**
     * 申请权限
     */
    private boolean requestPermission()
    {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    // 开始提交请求权限
    private void startRequestPermission()
    {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    /**
     * 注册权限申请回调
     *
     * @param requestCode  申请码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    thread = new AppUpdaterActivity.DownThread();
                    thread.start();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    thread = new AppUpdaterActivity.DownThread();
                    thread.start();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting()
    {
        dialog = new AlertDialog.Builder(this)
                .setCustomTitle(DialogTools.getDialgoTitleView(this, "部分权限不可用", R.mipmap.hintdialog))
                .setMessage("请在-应用设置-权限-中，打开存储权限，以保证应用正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    /**
     * 跳转到当前应用的设置界面
     */
    private void goToAppSetting()
    {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }


    /**
     * 下载线程
     *
     * @author Administrator
     */
    private class DownThread extends Thread
    {
        @Override
        public void run()
        {
            isDownload = true;
            download();
        }
    }

    /**
     * 下载
     */
    private void download()
    {
        // 得到下载地址；
        String url = getIntent().getStringExtra("url");
        new AppUpdaterNew(this).download(url, handler);
    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            isDownload = false;

            switch (msg.arg1) {
                case 0: // 下载成功
                    Intent intent = (Intent) msg.obj;
                    startActivity(intent);
                    finish();
                    break;

                case 1: // 下载失败
                    String txt = "下载失败，请重试。\n" + String.valueOf(msg.obj);
                    ((TextView) findViewById(R.id.textView1)).setText(txt);
                    // 隐藏掉进度条；
                    findViewById(R.id.progressBar1).setVisibility(View.INVISIBLE);
                    break;
            }
        }
    };

    @Override
    public void onBackPressed()
    {
        exit();
    }

    @Override
    protected void onDestroy()
    {
        mGlobalApp.removeActivity(this);
        super.onDestroy();
    }

    /**
     * 退出
     */
    private void exit()
    {
        if (isDownload)
            Toast.makeText(this, "正在下载程序，暂时不能取消...", Toast.LENGTH_SHORT).show();
        else
            finish();
    }
}
